package com.srwl.mytx.widget;

import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.activity.BaseActivity;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.CommentAdapter_v1;
import com.srwl.mytx.domain.Comment;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.CommentService;
import com.srwl.mytx.activity.UserProfileActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CommentView extends RelativeLayout implements CommentAdapter_v1.CommentClickListener {
    protected static final String TAG = "CommentView";
    protected InteractionListener listener;
    protected RecyclerView rv_commentList;
    private MaterialSmoothRefreshLayout refreshLayout;
    private View leftLayout;
    protected TextView tv_commentCount;
    protected CommentAdapter_v1 commentAdapter;
    protected List<Comment> commentList = new ArrayList<>();
    private Map praiseRecord;//被我点赞记录
    private Map commentPraiseSize;//点赞数量
    private int page = 1;
    private boolean hasNextPage;
    protected String topicId;
    private View titleBar;
    protected Context context;
    private Comment parentComment;
    protected Comment targetComment;
    //状态栏占位，当有视频的时候，全屏显示，但是评论框不能顶到屏幕顶部，需要留出状态栏的高度
    private View placeHolder;
    protected Integer commentSize;

    public CommentView(@NonNull Context context) {
        super(context);
        this.context = context;
        init(context);
    }

    public CommentView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init(context);
    }

    public CommentView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        init(context);
    }

    public CommentView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context);
    }

    private void init(@NonNull Context context) {
        inflate(context, R.layout.layout_comment_dialog_v1, this);
        placeHolder = findViewById(R.id.place_holder);
        rv_commentList = findViewById(R.id.rv_comment_list);
        titleBar = findViewById(R.id.title_bar);
        refreshLayout = findViewById(R.id.refresh_layout);
        leftLayout = findViewById(R.id.left_layout);
        tv_commentCount = findViewById(R.id.tv_comment_count);
        leftLayout.setOnClickListener(v -> {
            //  dismiss();
            listener.onHideCommentView();
        });

        commentAdapter = new CommentAdapter_v1(context, commentList, this);
        rv_commentList.setLayoutManager(new LinearLayoutManager(context));
        rv_commentList.setAdapter(commentAdapter);
        initRefreshLayout();

    }


    public void init(Topic topic, final InteractionListener listener) {
        this.listener = listener;
        this.topicId = topic.getId();
        commentSize = topic.getCommentSize();
        if (commentSize == null) {
            commentSize = 0;
            tv_commentCount.setText("暂无评论");

        } else {
            tv_commentCount.setText("共 " + commentSize + " 条评论");
        }
        commentList.clear();//必须清空，否则临时用户在主题页面登录后，评论回出现重复
        loadData(true);
    }

    public void setPlaceHolderHeight(int height) {
        ViewGroup.LayoutParams layoutParams = placeHolder.getLayoutParams();
        layoutParams.height = height;
        placeHolder.setLayoutParams(layoutParams);
    }

    public void scrollTitleBar(float slideOffset) {

        if (slideOffset == 1 && titleBar.isShown()) {
            titleBar.setVisibility(GONE);
        } else {
            if (slideOffset == 0 && !titleBar.isShown()) {
                titleBar.setVisibility(VISIBLE);
            }
        }

//        int scrollY = (int) (slideOffset * titleBarHeight);
//        titleBar.setTranslationY(-scrollY);//移动内容

        // rl_content.setTranslationY(-slideOffset * titleBarHeight);
    }

    private void initRefreshLayout() {
        refreshLayout.setNestedScrollingEnabled(false);
        refreshLayout.setDisableRefresh(true);
        refreshLayout.setDisableLoadMore(false);
        refreshLayout.setEnableOverScroll(true);
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {

            }

            @Override
            public void onLoadingMore() {
                if (hasNextPage) {
                    loadData(false);
                } else {
                    refreshLayout.refreshComplete();
                }
            }
        });
    }


    /**
     * 暂时不做考虑
     * 当账户改变的时候，需要去重新 获取消息，因为可能当前登录账户对本主题点过赞或者对某些评论点过赞
     */
    public void onAccountChange() {
        prepareComment();

    }

    public void loadData(boolean isFirst) {
        if (!Helper.getInstance().isNetworkConnected()) {
            if (!isFirst) refreshLayout.refreshComplete();
            Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }

        Map<String, Object> info = new HashMap<>();
        info.put("topicId", topicId);
        info.put("uId", UserProfileManager.getInstance().getLoginUserInfo().getuId());
        info.put("page", page);
        info.put("size", 10);
        RetrofitManager.getInstance().createRequest(CommentService.class)
                .getComment(info)
                .enqueue(new Callback<CommonResult>() {

                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                        refreshLayout.refreshComplete();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {

                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, result.getMsg());

                            return;
                        }
                        JSONObject jsonObject = (JSONObject) result.getData();

                        JSONObject pageInfo = jsonObject.getJSONObject("comments");
                        hasNextPage = pageInfo.getBoolean("hasNextPage");
                        if (!hasNextPage) {
                            refreshLayout.postDelayed(() -> refreshLayout.setFooterView(new NodataFooter(getContext())), 2000);
                            refreshLayout.setDisableLoadMore(true);
                        }
                        List<Comment> comments = pageInfo.getJSONArray("list").toJavaList(Comment.class);
                        Log.d(TAG, jsonObject.toJSONString());
                        if (page == 1) {
                            //  commentSize += jsonObject.getIntValue("commentSize");
                            if (comments.size() != 0) {
                                //以此来判别那些评论是被我点过赞
                                if (jsonObject.containsKey("praiseRecord")) {
                                    praiseRecord = JSONObject.parseObject(jsonObject.get("praiseRecord").toString(), Map.class);
                                }
                                if (jsonObject.containsKey("commentPraiseSize")) {

                                    commentPraiseSize = JSONObject.parseObject(jsonObject.get("commentPraiseSize").toString(), Map.class);
                                }
                            }


                        }
                        checkIsPraise(comments);
                        setupPraiseSize(comments);

                        commentList.addAll(comments);
                        commentAdapter.notifyDataSetChanged();
                        page++;

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                        refreshLayout.refreshComplete();
                        Log.e(TAG, t.getMessage());

                    }
                });
    }


    /**
     * 设置评论的点赞数量
     *
     * @param comments
     */
    void setupPraiseSize(List<Comment> comments) {
        if (commentPraiseSize == null || commentPraiseSize.size() == 0) {
            return;
        }
        for (Object o : commentPraiseSize.keySet()) {
            for (Comment comment : comments) {
                if (comment.getId().equals(o)) {
                    comment.setPraiseSize(Integer.valueOf(commentPraiseSize.get(o).toString()));
                }
            }
        }
    }


    /**
     * 检查哪些评论被我点过赞，点过赞的给与标记
     *
     * @param comments
     */
    void checkIsPraise(List<Comment> comments) {
        //先进行非空判断，然后遍历，把被我赞过的评论，做好标记
        if (praiseRecord == null || praiseRecord.size() == 0) {
            return;
        }
        for (Object o : praiseRecord.keySet()) {
            for (Comment comment : comments) {
                if (comment.getId().equals(o)) {
                    comment.setHadPraise(true);
                }
            }
        }
    }

    public void prepareComment() {
        targetComment = new Comment();
        //0表示是一条普通评论，针对主题的评论
        targetComment.setType(Constant.COMMENT_TYPE_NORMAL);
        targetComment.setTopicId(topicId);
        targetComment.setFromUid(UserProfileManager.getInstance().getLoginUserInfo().getuId());
        targetComment.setFromAvatar(UserProfileManager.getInstance().getLoginUserInfo().getAvatar());
        targetComment.setFromNick(UserProfileManager.getInstance().getLoginUserInfo().getUsername());
    }

    public void commitComment(String content) {
        try {
            targetComment = (Comment) targetComment.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        targetComment.setContent(content);
        if (targetComment.getType() == Constant.COMMENT_TYPE_NORMAL) {
            commitNormalComment();
        } else {
            commitChildComment();
        }

    }


    /**
     * 提交一个普通评论
     */
    protected void commitNormalComment() {
        if (!Helper.getInstance().isNetworkConnected()) {
            Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        RetrofitManager.getInstance().createRequest(CommentService.class)
                .createComment(targetComment)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            if (listener != null) {
                                listener.onCreateCommentError();
                            }
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, result.getMsg());
                            if (result.getStatus().equals(Constant.COMMENT_SIZE_UPDATED_FAILED)) {
                                Toast.makeText(context, "评论失败！该主题可能已被删除。", Toast.LENGTH_SHORT).show();
                            } else if (listener != null) {
                                listener.onCreateCommentError();
                            }
                            return;
                        }
                        Log.i(TAG, "onResponse: 创建普通评论完成");
                        commentSize++;
                        tv_commentCount.setText("共 " + commentSize + " 条评论");
                        String c_id = result.getData() + "";
                        targetComment.setId(c_id);
                        //把评论插到第一个的位置
                        commentList.add(0, targetComment);
                        commentAdapter.notifyItemInserted(0);
                        commentAdapter.notifyItemRangeChanged(0, commentList.size());
                        rv_commentList.smoothScrollToPosition(0);
                        if (listener != null) {
                            listener.onCreateNormalCommentSuccess();
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        if (listener != null) {

                            listener.showToast(context.getString(R.string.system_busy));
                        }
                    }
                });
    }


    /**
     * 创建子评论----就是评论中的回复
     */
    protected void commitChildComment() {
        if (!Helper.getInstance().isNetworkConnected()) {
            Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        commentAdapter.setForbiddenItemClick(true);//添加子评论的时候，禁用 评论项的点击，避免位置错乱
        RetrofitManager.getInstance().createRequest(CommentService.class)
                .createChildComment(targetComment)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            if (listener != null) {
                                listener.onCreateCommentError();
                            }
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, result.getMsg());
                            if (result.getStatus().equals(Constant.COMMENT_SIZE_UPDATED_FAILED)) {
                                Toast.makeText(context, "评论失败！该主题可能已被删除。", Toast.LENGTH_SHORT).show();
                            } else if (listener != null) {
                                listener.onCreateCommentError();
                            }
                            return;
                        }
                        Log.i(TAG, "onResponse: 创建子评论完成");
                        commitChildCommentComplete();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        if (listener != null) {
                            listener.onCreateCommentError();
                        }
                        commentAdapter.setForbiddenItemClick(false);

                    }
                });
    }

    protected void commitChildCommentComplete() {
        commentSize++;
        tv_commentCount.setText("共 " + commentSize + " 条评论");
        parentComment.addChildSize();
        parentComment.addChildComment(targetComment);//让父评论和子评论互相持有
        targetComment.setParentComment(parentComment);
        commentAdapter.addChildCommentComplete_v1(parentComment, targetComment);

        if (listener != null) {
            listener.onCreateChildCommentSuccess();
        }
    }


    public void setListener(InteractionListener listener) {
        this.listener = listener;
    }

    @Override
    public void commentItemLongClick(int comment) {
        showBottomDialog(comment);
    }

    @Override
    public void avatarClick(User targetUser) {
        context.startActivity(new Intent(context, UserProfileActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, targetUser));

    }

    @Override
    public void commentItemClick(Comment parentComment, int position) {

        Comment childComment = new Comment();
        //1表示是这是一条子评论
        childComment.setType(Constant.COMMENT_TYPE_CHILD);
        childComment.setTopicId(topicId);
        childComment.setParentId(parentComment.getId());
        childComment.setFromUid(UserProfileManager.getInstance().getLoginUserInfo().getuId());
        childComment.setFromAvatar(UserProfileManager.getInstance().getLoginUserInfo().getAvatar());
        childComment.setFromNick(UserProfileManager.getInstance().getLoginUserInfo().getUsername());
        this.parentComment = parentComment;
        targetComment = childComment;
        if (listener != null) {
            listener.onCommentItemClick("回复： " + parentComment.getFromNick());
        }
    }

    @Override
    public void childCommentItemClick(Comment parentComment, int position, User replyTarget) {

        Comment childComment = new Comment();
        //2表示是子评论的回复
        childComment.setType(Constant.COMMENT_TYPE_CHILD_REPLY);
        childComment.setTopicId(topicId);
        childComment.setParentId(parentComment.getId());
        childComment.setFromUid(UserProfileManager.getInstance().getLoginUserInfo().getuId());
        childComment.setFromAvatar(UserProfileManager.getInstance().getLoginUserInfo().getAvatar());
        childComment.setFromNick(UserProfileManager.getInstance().getLoginUserInfo().getUsername());
        childComment.setToUid(replyTarget.getuId());
        childComment.setToNick(replyTarget.getUsername());
        childComment.setToAvatar(replyTarget.getAvatar());
        this.parentComment = parentComment;
        targetComment = childComment;
        if (listener != null) {
//            listener.onCommentItemClick("回复： " + parentComment.getFromNick());
            listener.onCommentItemClick("回复：" + replyTarget.getUsername());   //回复当前子评论的用户
        }
    }

    @Override
    public void addCommentPraise(Comment targetComment, int position) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity) context).showToast_v1(context.getString(R.string.network_anomalies));
            return;
        }
        Map<String, Object> info = new HashMap<>();
        info.put("topicId", topicId);
        info.put("commentId", targetComment.getId());
        RetrofitManager.getInstance().createRequest(CommentService.class)
                .commentPraise(info)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            return;
                        }
                        Log.d(TAG, "onResponse: 添加评论点赞完成");

//                                commentList.get(position).setHadPraise(true);
//                                commentAdapter.notifyItemChanged(position);

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                    }
                });
    }

    @Override
    public void removeCommentPraise(Comment targetComment, int position) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity) context).showToast_v1(context.getString(R.string.network_anomalies));
            return;
        }
        Map<String, Object> info = new HashMap<>();
        info.put("topicId", topicId);
        info.put("commentId", targetComment.getId());
        RetrofitManager.getInstance().createRequest(CommentService.class)
                .removeCommentPraise(info)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            return;
                        }
                        Log.d(TAG, "onResponse: 去除评论点赞完成");
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                    }
                });
    }

    @Override
    public void clearCommentTarget() {
        //重新生成普通评论对象
        prepareComment();
        if (listener != null) {
            listener.onCreateNormalCommentSuccess();
        }
    }

    private void showBottomDialog(final int position) {
        final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(context, R.style.BottomDialog);
        View view = LayoutInflater.from(context).inflate(R.layout.comment_bottom_dialog, null);
        //删除评论
        /*if (UserProfileManager.getInstance().getUserID().equals(commentList.get(position).getFromUid())){
            view.findViewById(R.id.rl_delete).setVisibility(VISIBLE);
        }else {
            view.findViewById(R.id.rl_delete).setVisibility(GONE);
        }
        view.findViewById(R.id.rl_delete).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //删除当前条item
                commentAdapter.notifyItemRemoved(position);
                commentList.remove(position);
                commentAdapter.notifyItemRangeChanged(position,commentAdapter.getItemCount());

            }
        });*/
        view.findViewById(R.id.rl_accusation).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog.dismiss();
                accusationComment(commentList.get(position));

            }
        });
        view.findViewById(R.id.rl_cancle).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog.dismiss();
            }
        });
        bottomSheetDialog.setContentView(view);
        bottomSheetDialog.show();
    }

    /**
     * 举报评论
     *
     * @param comment
     */
    void accusationComment(Comment comment) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity) context).showToast_v1(context.getString(R.string.network_anomalies));
            return;
        }
        if (listener != null) {
            listener.showProgressBar(true);
        }
        RetrofitManager.getInstance().createRequest(CommentService.class)
                .accusationComment(comment.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (listener != null) {
                            listener.showProgressBar(false);
                        }
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            if (listener != null) {
                                listener.showToast(context.getString(R.string.system_busy));
                            }
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            if (listener != null) {
                                listener.showToast(context.getString(R.string.system_busy));
                            }
                        }
                        Log.d(TAG, "onResponse: 举报完成");

                        if (listener != null) {
                            listener.showToast(context.getString(R.string.accusation_complete));
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (listener != null) {
                            listener.showProgressBar(false);
                        }
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

    public interface InteractionListener {

        void onHideCommentView();

        void onLoadCommentSuccess(boolean hasNextCommentPage);

        void onLoadCommentError();

        void showToast(String message);

        void firstLoadDataComplete(int topicPraiseSize, boolean hadPraise);

        void onCreateNormalCommentSuccess();

        void onCreateChildCommentSuccess();

        void onCreateCommentError();

        void showProgressBar(boolean isShowProgressBar);

        void onCommentItemClick(String hint);
    }
}
